package com.hll.javaee.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CookieDemo extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // cookie是客户端你维持状态的解决方案
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=utf-8"); // 没设这两个容易乱码
    response.setCharacterEncoding("UTF-8");

    Cookie[] cookies = request.getCookies(); // 客户端所有cookie
    PrintWriter writer = response.getWriter();
    if (cookies != null) { // 如果有一个cookie的话
      writer.print("你上一次访问的时间: ");
      for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        if (cookie.getName().equals("last")) { // name是"last"的cookie
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          Long times = Long.parseLong(cookie.getValue());
          Date date = new Date(times);
          String dateNowStr = sdf.format(date);
          writer.write(dateNowStr);
          // writer.write(URLDecoder.decode(cookie.getValue(), "UTF-8"));
        }
      }
    } else {
      writer.write("这是第一次访问本站");
    }
    // 新建cookie
    // Cookie cookie = new Cookie("last", URLEncoder.encode("胡龙龙", "UTF-8"));
    // 可以直接写"XXX",按照utf编码后需要解码才能还原, 检查页面-application-cookies可以看到
    Cookie cookie = new Cookie("last", System.currentTimeMillis() + ""); // cookie只能存字符串
    cookie.setMaxAge(10); // 存活时间 单位/s
    response.addCookie(cookie); // 返回给客户端设置
  }
}
